from django.shortcuts import render, redirect
from . import models
from . import forms


# Create your views here.

def index(request):
    if not request.session.get('is_login', None):
        return redirect('/login/')
    user_item = models.User.objects.get(user_name=request.session['user_name'])
    if not user_item.thing_all == 0:
        schedule_item = models.Schedule.objects.filter(create_by=request.session['user_name'])[:10]
        if not user_item.thing_wait == 0:
            wait_finish = models.Schedule.objects.filter(create_by=request.session['user_name'], status="未完成")[:10]
    return render(request, 'sims/index.html', locals())


def login(request):
    login_form = forms.LoginForm()
    if request.session.get('is_login', None):
        return redirect('/index/')
    if request.method == 'POST':
        login_form = forms.LoginForm(request.POST)
        if login_form.is_valid():
            username = login_form.cleaned_data.get('username')
            password = login_form.cleaned_data.get('password')
            try:
                user = models.User.objects.get(user_name=username)
            except:
                message_warn = '用户不存在'
                return render(request, 'sims/login.html', locals())
            if user.user_psw == password:
                request.session["is_login"] = True
                request.session["user_id"] = user.user_id
                request.session["user_name"] = user.user_name
                return redirect('sims:index')
            else:
                message_warn = "密码不正确!"
                return render(request, 'sims/login.html', locals())
    return render(request, 'sims/login.html', locals())


def logout(request):
    if not request.session.get('is_login', None):
        return redirect('/login/')
    request.session.flush()
    return redirect("/login/")


def register(request):
    register_form = forms.RegisterForm()
    if request.session.get('is_login', None):
        return redirect('/index/')
    if request.method == 'POST':
        register_form = forms.RegisterForm(request.POST)
        if register_form.is_valid():
            username = register_form.cleaned_data.get('username')
            real_name = register_form.cleaned_data.get('real_name')
            password = register_form.cleaned_data.get('password')
            password_confirm = register_form.cleaned_data.get('password_confirm')
            email = register_form.cleaned_data.get('email')
            user_id = register_form.cleaned_data.get('user_id')

            if password_confirm != password:
                message_warn = '两次输入的密码不一致!'
                return render(request, 'sims/register.html', locals())
            else:
                same_username = models.User.objects.filter(user_name=username)
                if same_username:
                    message_warn = '用户名已存在'
                    return render(request, 'sims/register.html', locals())
                same_email = models.User.objects.filter(user_email=email)
                if same_email:
                    message_warn = '该邮箱地址已被注册'
                    return render(request, 'sims/register.html', locals())
                same_user_id = models.User.objects.filter(user_id=user_id)
                if same_user_id:
                    message_warn = '该学号已存在'
                    return render(request, 'sims/register.html', locals())
                new_user = models.User()
                new_user.user_name = username
                new_user.user_psw = password
                new_user.user_id = user_id
                new_user.user_email = email
                new_user.user_real_name = real_name
                new_user.save()
                return redirect('/register_success/')
        else:
            return render(request, 'sims/register.html', locals())
    return render(request, 'sims/register.html', locals())


def register_success(request):
    return render(request, 'sims/register_success.html', locals())


def schedule(request):
    if not request.session.get('is_login', None):
        return redirect('/login/')
    user_item = models.User.objects.get(user_name=request.session['user_name'])
    schedule_form = forms.ScheduleForm()
    edit_schedule_form=forms.EditScheduleForm()
    if not user_item.thing_all == 0:
        schedule_item = models.Schedule.objects.filter(create_by=request.session['user_name'])

    if request.method == 'POST':
        schedule_form = forms.ScheduleForm(request.POST)
        edit_mode = "cannot_edit"
        # edit_mode=request.POST.get('edit_mode')
        # if not edit_mode=="cannot_edit":
            # target_edit=models.Schedule.objects.get(create_by=request.session['user_name'],
            #                                          title=edit_mode)
            # edit_schedule_form = forms.EditScheduleForm(request.POST)
            # editor=models.Editor.objects.get(type="key")
            # editor.title=target_edit.title
            # editor.theme=target_edit.theme
            # editor.content=target_edit.content
            # editor.important_level=target_edit.important_level
            # editor.alert_mode=target_edit.alert_mode
            # editor.status=target_edit.status
            # editor.start_date=target_edit.start_date
            # editor.end_date=target_edit.end_date
            # editor.save()
            # if edit_schedule_form.is_valid():
            #     title = edit_schedule_form.cleaned_data.get("title")
            #     content = edit_schedule_form.cleaned_data.get("content")
            #     start_date = edit_schedule_form.cleaned_data.get('start_date')
            #     end_date = edit_schedule_form.cleaned_data.get('end_date')
            #     theme = edit_schedule_form.cleaned_data.get('theme')
            #     important_level = edit_schedule_form.cleaned_data.get('important_level')
            #     # status = schedule_form.cleaned_data.get('status')
            #     alert_mode = edit_schedule_form.cleaned_data.get('alert_mode')
            #
            #     same_title = models.Schedule.objects.filter(title=title)
            #
            #     if not same_title:
            #         target_edit.title = title
            #         target_edit.content = content
            #         target_edit.start_date = start_date
            #         target_edit.end_date = end_date
            #         target_edit.theme = theme
            #         target_edit.important_level = important_level
            #         target_edit.alert_mode = alert_mode
            #         target_edit.save()
            #         message_success = "日程修改成功！"
            #         edit_mode = request.POST.get('edit_mode')
            #     else:
            #         message_warn = "存在相同的标题!"
                    # return render(request, 'sims/schedule.html', locals())
        try:
            target_del = models.Schedule.objects.get(create_by=request.session['user_name'],
                                                     title=request.POST.get("del"))
            if target_del:
                new_history = models.History()
                new_history.history_key = request.session.get('user_name', None)
                new_history.thing_finished = target_del.title
                new_history.history_type = "删除"
                user_item.thing_all -= 1
                if not target_del.status == "已完成":
                    user_item.thing_wait -= 1
                new_history.save()
                target_del.delete()
                message_success = "删除成功!"
                return render(request, 'sims/schedule.html', locals())
        except:
            pass
        if schedule_form.is_valid():
            title = schedule_form.cleaned_data.get("title")
            content = schedule_form.cleaned_data.get("content")
            start_date = schedule_form.cleaned_data.get('start_date')
            end_date = schedule_form.cleaned_data.get('end_date')
            theme = schedule_form.cleaned_data.get('theme')
            important_level = schedule_form.cleaned_data.get('important_level')
            status = schedule_form.cleaned_data.get('status')
            alert_mode = schedule_form.cleaned_data.get('alert_mode')

            same_title = models.Schedule.objects.filter(title=title,create_by=request.session['user_name'])

            if not same_title:
                user_item.thing_all += 1
                user_item.thing_wait += 1
                user_item.save()
                new_schedule = models.Schedule()
                new_schedule.title = title
                new_schedule.content = content
                new_schedule.start_date = start_date
                new_schedule.end_date = end_date
                new_schedule.theme = theme
                new_schedule.important_level = important_level
                new_schedule.status = "未完成"
                new_schedule.alert_mode = alert_mode
                new_schedule.create_by = request.session.get('user_name', None)
                new_schedule.save()
                message_success = "日程添加成功！"
                return render(request, 'sims/schedule.html', locals())
            else:
                message_warn = "存在相同的标题!"
                return render(request, 'sims/schedule.html', locals())

    return render(request, 'sims/schedule.html', locals())


def history(request):
    if not request.session.get('is_login', None):
        return redirect('/login/')
    user_item = models.User.objects.get(user_name=request.session['user_name'])
    if not user_item.thing_finished == 0:
        finished_item = models.History.objects.filter(history_key=request.session['user_name'])
    return render(request, 'sims/history.html', locals())


def user_control(request):
    if not request.session.get('is_login', None):
        return redirect('/login/')
    user_item = models.User.objects.get(user_name=request.session['user_name'])
    control_form = forms.ControlForm()
    if request.method == 'POST':
        control_form = forms.ControlForm(request.POST)

        if control_form.is_valid():
            # 修改密码表单
            old_psw = control_form.cleaned_data.get('old_psw')
            new_psw = control_form.cleaned_data.get('new_psw')
            new_psw_confirm = control_form.cleaned_data.get('new_psw_confirm')

            # 修改密码功能
            if old_psw:
                if new_psw != new_psw_confirm:
                    message_warn = '两次输入密码不一致'
                    return render(request, 'sims/user_control.html', locals())
                else:
                    if old_psw != models.User.objects.get(user_name=request.session.get('user_name', None)).user_psw:
                        message_warn = '原密码不正确'
                        return render(request, 'sims/user_control.html', locals())
                    else:
                        message_success = '密码修改成功'
                        current_user = models.User.objects.get(user_name=request.session.get('user_name', None))
                        current_user.user_psw = new_psw
                        current_user.save()
                        return render(request, 'sims/user_control.html', locals())
    return render(request, 'sims/user_control.html', locals())


def to_do(request):
    if not request.session.get('is_login', None):
        return redirect('/login/')
    user_item = models.User.objects.get(user_name=request.session['user_name'])
    if not user_item.thing_wait == 0:
        thing_wait = models.Schedule.objects.filter(create_by=request.session['user_name'], status="未完成")
        thing_important = 0
        thing_common = 0
        thing_unimportant = 0
        for foo in thing_wait:
            if foo.important_level == "重要":
                thing_important += 1
            elif foo.important_level == "一般":
                thing_common += 1
            else:
                thing_unimportant += 1

    if request.method == "POST":
        target = models.Schedule.objects.get(create_by=request.session['user_name'], title=request.POST.get("finished"))
        target.status = "已完成"
        user_item.thing_finished += 1
        user_item.thing_wait -= 1
        target.save()
        user_item.save()
        new_history = models.History()
        new_history.history_key = request.session.get("user_name", None)
        new_history.thing_finished = target.title
        new_history.history_type = "完成"
        new_history.save()
        message_success = "太棒了!"
    return render(request, 'sims/to_do.html', locals())
